<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/6
 * Time: 17:04
 */

namespace app\admin\controller;
use think\Request;
use think\Db;
use think\Session;
use think\Controller;
use think\Cache;

class LoginController extends Controller
{
    //登陆
    public function login()
    {
        $request = Request::instance();
        switch ($request->method()) {
            case "GET":
                return $this->fetch();
                break;
            case "POST":
                $params = $request->param();

                if(!captcha_check($params['yzm'])){
                    $this->assign('info','验证码输入有误');
                    return $this->fetch();
                }
                $map = [];
                $map['name'] = $params['name'];
                $map['password'] = md5($params['password']);
                $staff = Db::table('staff')->where('status','eq',1)->where($map)->find();
                if($staff){
                    Session::set('staff',$staff);
//                    $list = Db::query("select n.controller,n.action from staff_role sr,role_node rn,node n where n.status=1 and sr.role_id=rn.role_id and rn.node_id=n.id and sr.staff_id=".$staff['id']);
//                    $nodeList['index'][] = 'index';
//                    $nodeList['login'][] = 'logOut';
//                    $nodeList['login'][] = 'login';
//
//                    foreach($list as $v){
//                        $nodeList[$v['controller']][] = $v['action'];
//                    }
//                    foreach($nodeList as $a=>$b){
//                        $nodeList[$a] = array_unique($b);
//                    }
//                    Session::set('nodeList',$nodeList);
                    $this->success('登陆成功,正在跳转到首页',url('admin/index/index'),'',1);
//                }
//                else{
//                    $this->assign('info','用户名与密码不匹配');
//                    return $this->fetch();
                }
                break;
            default:
                return "错误的数据信息";
        }
    }

    //退出
    public function logOut()
    {
        Session::delete('staff');
        Session::delete('nodeList');
        $this->redirect('admin/login/login');
    }

    //清除缓存
    public function clearCache()
    {
        if(Cache::clear() && $this->delTemp()){
            return true;
        }
        return false;
    }

    //删除模板缓存文件
    private function delTemp()
    {
        $temp = RUNTIME_PATH.'temp/';
        if(is_dir($temp)){
            $dh = opendir($temp);
            while($filename = readdir($dh)){
                $newPath = $temp.$filename;
                if(is_file($newPath)){
                    unlink($newPath);
                }
            }
            closedir($dh);
            return true;
        }
        return false;
    }
}